const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
//实现深拷贝
const deepClone = function (obj) {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj[key] && typeof obj[key] === 'object') {
        objClone[key] = deepClone(obj[key]);
      } else {
        objClone[key] = obj[key]
      }
    }
  }
  return objClone;
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}



//节流函数 用来防止移动高频触发
const throttle = function (func, delay) {
  let timerId = null;
  let lastExecTime = 0;

  return function (...args) {
    const currentTime = Date.now();

    if (currentTime - lastExecTime < delay) {
      clearTimeout(timerId);

      timerId = setTimeout(() => {
        lastExecTime = currentTime;
        func.apply(this, args);
      }, delay);
    } else {
      lastExecTime = currentTime;
      func.apply(this, args);
    }
  }
};
//获得用户头像
//对获取用户头像等信息进行promise封装
const getUserdata = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '获取你的昵称、头像',
      success: (res) => {
        resolve(res)
      },

      fail: (err) => {
        //拒绝授权
        wx.showToast({
          title: '您拒绝了请求,不能正常使用小程序',
          icon: 'error',
          duration: 2000
        })
        reject(err)
      }

    })
  })
};

//实现文件上传
const uploadFile = (filepath, name, url) => {
  return new Promise((resolve, reject) => {
    if (!filepath || filepath.length === 0) {
      reject(new Error("No file uploaded."));
      return;
    }
    wx.uploadFile({
      filePath: filepath,
      name: name,
      url: url,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
//下载临时文件
const downloadFile = (filepath) => {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url: filepath,
      success: (downloadRes) => {
        if (downloadRes.statusCode === 200) {
          const savedFilePath = downloadRes.tempFilePath;
          resolve(savedFilePath)
        } else {
          console.error('Download file failed:', downloadRes.statusCode);
          // 下载文件失败的处理逻辑
        }
      },
      fail: (error) => {
        console.error('Download file failed:', error);
        // 下载文件失败的处理逻辑
      }
    })
  })
}
module.exports = {
  formatTime,
  throttle,
  getUserdata,
  uploadFile,
  downloadFile,
  deepClone
}